//
//  KFDInvestmentCommunityPostListViewController.m
//  
//
//  Created by JIRENTIANXIANG on 6/26/15.
//
//

#import "KFDInvestmentCommunityPostListViewController.h"
#import "KFDInvestmentCommunityPostListViewModel.h"
#define KFDInvestmentCommunityPostCellReuseIdentifier @"KFDInvestmentCommunityPostCell"
#define KFDInvestmentCommunityPostCellNibName @"KFDInvestmentCommunityPostCell"
#import "KFDUIConfigurator.h"
#import "ui_config.h"
#import "KFDNewPostViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "KFDInvestmentCommunityViewCell.h"
#import "UIView+KeyboardObserver.h"
#include "KFDICCommentViewController.h"
#import "KFDAccountManager.h"
#import "UIAlertController+KFD.h"
#import "JRTXLinearLayout.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface KFDInvestmentCommunityPostListViewController ()

@property (strong,nonatomic) KFDInvestmentCommunityPostListViewModel* viewModel;
@property (strong,nonatomic) UIView* commentFieldContainer;
@property (strong,nonatomic) UITextField* commentField;
@property (strong,nonatomic) UIImageView* avatar;
@property (strong,nonatomic) UILabel* nameLabel;

@end

@implementation KFDInvestmentCommunityPostListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigationBar];
    [self setupHeader];
    [self setupAvatar];
    [self setupNameLabel];
    [self addNotificationObservers];
    [self setupViewModel];
    [self setupRefreshing];
}

-(void)setupNavigationBar
{
    KFDUIConfigurator* uiConfigurator=[KFDUIConfigurator configuratorForViewController:self];
    [uiConfigurator configureNavigationBarWithBackAction:@selector(goBack)];
    self.title=@"投资圈";
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"header-publish-ico"] style:UIBarButtonItemStylePlain target:self action:@selector(newPost)];
}

-(void)setupHeader
{
    UIImageView* headerView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 190)];
    headerView.image=[UIImage imageNamed:@"usercenter-header-bg.png"];
    self.tableView.tableHeaderView=headerView;
}

-(void)setupAvatar
{
    KFDUIConfigurator* uiConfigurator=[KFDUIConfigurator configuratorForViewController:self];
    self.avatar=[UIImageView new];
    self.avatar.frame=CGRectMake(0, 0, 80, 80);
    self.avatar.center=CGPointMake(uiConfigurator.WIDTH/2, 100);
    self.avatar.layer.cornerRadius=80/2;
    self.avatar.layer.masksToBounds=YES;
    [self.view addSubview:self.avatar];
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:accountManager.avatar] placeholderImage:[UIImage imageNamed:@"avatar"]];
}

-(void)setupNameLabel
{
    self.nameLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.nameLabel.center=CGPointMake(SCREEN_WIDTH/2, 150);
    self.nameLabel.textAlignment=NSTextAlignmentCenter;
    self.nameLabel.font=[UIFont systemFontOfSize:15];
    self.nameLabel.textColor=KFD_WHITE;
    [self.view addSubview:self.nameLabel];
}

-(void)setupViewModel
{
    self.viewModel=[[KFDInvestmentCommunityPostListViewModel alloc] init];
    [self.viewModel loadPostsWithMaxCount:20 page:1];
}

-(void)setupRefreshing
{
    __weak typeof(self) weakSelf=self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf.viewModel loadPostsWithMaxCount:weakSelf.viewModel.posts.count page:1];
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf.viewModel loadPostsWithMaxCount:weakSelf.viewModel.posts.count+10 page:1];
    }];
}

-(void)addNotificationObservers
{
    NSNotificationCenter* center=[NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(postsReadyWithNotification:) name:KFDInvestmentCummunityPostsReadyNotification object:nil];
    [center addObserver:self selector:@selector(updatePostListView) name:KFDICCommentCompletionNotification object:nil];
    [center addObserver:self selector:@selector(updatePostListView) name:KFDICRepraisedNotification object:nil];
}

-(void)updatePostListView
{
    [self.viewModel loadPostsWithMaxCount:self.viewModel.posts.count page:1];
}

-(void)dealloc
{
    NSNotificationCenter* center=[NSNotificationCenter defaultCenter];
    [center removeObserver:self name:KFDInvestmentCummunityPostsReadyNotification object:nil];
    [center removeObserver:self name:KFDICCommentCompletionNotification object:nil];
    [center removeObserver:self name:KFDICRepraisedNotification object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    self.nameLabel.text=accountManager.nickname;
}

-(void)newPost
{
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    if (accountManager.isLogin) {
        UIViewController* newPostVC=[[KFDNewPostViewController alloc] init];
        [self.navigationController pushViewController:newPostVC animated:YES];
    }else{
        [UIAlertController presentLoginRegisterAlertControllerWithMessage:@"发表心得前请先登录" byViewController:self];
    }
}

-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)postsReadyWithNotification:(NSNotification*)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self.tableView.header isRefreshing]) {
            [self.tableView.header endRefreshing];
        }
        if ([self.tableView.footer isRefreshing]) {
            [self.tableView.footer endRefreshing];
        }
        [self.tableView reloadData];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.posts.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KFDInvestmentCommunityViewCell* cell=[[KFDInvestmentCommunityViewCell alloc] init];
    [cell setup];
    cell.post=self.viewModel.posts[indexPath.row];
    return [cell layout];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KFDInvestmentCommunityViewCell* cell=[[KFDInvestmentCommunityViewCell alloc] init];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.viewController=self;
    [cell setup];
    cell.post=self.viewModel.posts[indexPath.row];
    [cell layout];
    __weak typeof(self) weakSelf=self;
    __weak typeof(cell) weakCell=cell;
    cell.commentAction=^{
        KFDICCommentViewController* commentVC=[[KFDICCommentViewController alloc] init];
        commentVC.post=weakCell.post;
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
            commentVC.modalPresentationStyle=UIModalPresentationOverCurrentContext;
        }else{
            weakSelf.modalPresentationStyle=UIModalPresentationCurrentContext;
        }
        [weakSelf presentViewController:commentVC animated:YES completion:nil];
    };
    return cell;
}

-(void)resignCommentField
{
    [self.commentField resignFirstResponder];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
